package com.test.springai.controller;

import com.alibaba.cloud.ai.dashscope.api.DashScopeImageApi;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 8/19/25 2:58 PM
 * @modifiedBy:
 * @version: 1.0
 */
@RestController
@Slf4j
public class ImageController {
  @Autowired private DashScopeImageModel imageModel;

  @GetMapping("/image")
  public void getImage(
      @RequestParam(value = "msg", defaultValue = "生成一只小猫") String msg,
      HttpServletResponse response) {
    final ImageResponse imageResponse =
        imageModel.call(
            new ImagePrompt(
                msg,
                DashScopeImageOptions.builder()
                    .withModel(DashScopeImageApi.DEFAULT_IMAGE_MODEL)
                    .withN(1)
                    .withHeight(1024)
                    .withWidth(1024)
                    .build()));
    // 获取生成图片URL地址
    final String imageUrl = imageResponse.getResult().getOutput().getUrl();
    try {
      URL url = URI.create(imageUrl).toURL();
      InputStream in = url.openStream();
      response.setContentType("image/jpeg");
      response.getOutputStream().write(in.readAllBytes());
      response.getOutputStream().flush();
    } catch (IOException e) {
      log.error("生成图片转换到页面错误", e);
    }
  }
}
